package com.example.oj.service;

import com.example.oj.commondUtil.CreateChildProcess;
import com.example.oj.model.Question;
import com.example.oj.model.Answer;
import com.sun.org.apache.bcel.internal.classfile.Code;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.UUID;

@Service
public class TaskService {
    //约定所有临时文件所在的目录
    private String WORK_DIR = null;
    //约定代码的类名
    private String CLASS = null;
    //约定要编译的代码文件名
    private String CODE = null;
    //约定存放编译错误信息的文件名
    private String COMPILE_ERROR = null;
    //约定存放运行时存放标准输出的文件名
    private String STDOUT = null;
    //约定存放运行时存放标准错误的文件名
    private String STDERR = null;
    public TaskService(){
        //使用UUID这个类生成一个UUID
        WORK_DIR = "./src/main/java/com/example/oj/tmp/" + UUID.randomUUID().toString() + "/";
        CLASS = "Solution";
        CODE = WORK_DIR + "Solution.java";
        COMPILE_ERROR = WORK_DIR + "compileError.txt";
        STDOUT = WORK_DIR + "stdout.txt";
        STDERR = WORK_DIR + "stderr.txt";
    }
    @Autowired
    private CreateChildProcess childProcess;
    public Answer compileAndRun(Question question){
        Answer answer = new Answer();
        File workDir = new File(WORK_DIR);
        if (!workDir.exists()){
            workDir.mkdirs();
        }
        FileUtil.writeFile(CODE,question.getCode());
        String compileCmd = String.format("javac -encoding utf8 %s -d %s",CODE,WORK_DIR);
        childProcess.run(compileCmd,null,COMPILE_ERROR);
        String compileError = FileUtil.readFile(COMPILE_ERROR);
        if (!compileError.equals("")){
            //编译出错
            System.out.println("编译出错");
            answer.setError("编译出错");
            answer.setReason(compileError);
            return answer;
        }
        String runCmd = String.format("java -classpath %s %s",WORK_DIR,CLASS);
        System.out.println(runCmd);
        childProcess.run(runCmd,STDOUT,STDERR);
        String runError = FileUtil.readFile(STDERR);
        if(!runError.equals("")){
            answer.setError("运行出错");
            answer.setReason(runError);
            System.out.println("运行出错");
            return answer;
        }
        answer.setError("执行完毕");
        answer.setStdout(FileUtil.readFile(STDOUT));
        return answer;
    }
}
